/*
 * zend 脚本,固定命名空间
 */
var zendform = {
	
	version : "hipop@126.com 1.0.0.1",
	/**
	 * 私有函数 zend表单html的处理
	 */
	_zendRenderFilteForm : function(htmlstr,e,arg){
		if(!htmlstr.match(/^<form.+id=.+$/mi)){
			arg.form.id && (htmlstr = htmlstr.replace("<form","<form id='"+arg.form.id+"'"));
		}
		if(!htmlstr.match(/^<form.+name=.+$/mi)){
			arg.form.name && (htmlstr = htmlstr.replace("<form","<form name='"+arg.form.name+"'"));
		}
		return htmlstr;
	},
	
	/**
	 * 全局函数 zend表单创建条目时的集中处理方法。
	 * 渲染表单
	 */
	zendRenderCreatForm : function(htmlStr,ishtml,Did,e,arg){
		ishtml = ishtml || false;
		if(ishtml){
			htmlStr = this._zendRenderFilteForm(htmlStr,e,arg);
			$("#"+Did).html(htmlStr).dialog("show");	
			
			//切点 C :afterRenderCreatForm 表单渲染之后
			if(typeof arg.afterRenderCreatForm == "function"){
				//切点c的回调参数 e，arg，dialog的最终参数项目,在其中，可改变Ddiv变量来改变div的html内容
				var rs = arg.afterRenderCreatForm(e,arg,Did) || false;
				//如果回调返回的是cancel，那么终止程序。
				if(rs == "cancel") return;
			}
			//切点c 结束
		}else{
			if(htmlStr != undefined){
				$.ajax({
					"url":htmlStr,///user/creat",
					"dataType":"text",
					"dataType": "html", //text，脚本没法运行？
					"type":"GET",
					"success":function(data){
						data = zendform._zendRenderFilteForm(data,e,arg);
						$("#"+Did).html(data).dialog("show");
						
						//切点 C :afterRenderCreatForm 表单渲染之后
						if(typeof arg.afterRenderCreatForm == "function"){
							//切点c的回调参数 e，arg，dialog的最终参数项目,在其中，可改变Ddiv变量来改变div的html内容
							var rs = arg.afterRenderCreatForm(e,arg,Did) || false;
							//如果回调返回的是cancel，那么终止程序。
							if(rs == "cancel") return;
						}
						//切点c 结束
					},
					"error":function(){
						$("<div>ERROR!表单数据获取失败</div>").dialog({title:"ERROR!",height: 140,modal: true});
						$("#"+Did).html("ERROR!表单数据获取失败，请检查网路。").dialog("show");
					}
				});
			}else{
			}
		}
		//处理错误提示，点击出错的提示就把它remove掉
		$("#"+Did + " ul.errors").click(function(){
			$(this).prev("input").focus();
			$(this).remove();
		});
		//处理错误提示，空间获取焦点就把提示remove掉
		$("#"+Did + " ul.errors").prev("input").focus(function(){
			$(this).next("ul.errors").remove();
		});
	},
	
	/**
	 * 全局函数 zend表单创建条目时的集中处理方法。
	 * @e grid，来自grid按钮的回调
	 * @param arg arg中包含一个form集合
	 * @returns
	 */
	zendFormCreat : function(e,arg){
		arg = $.extend({
			url:"",//获取form的url
			dialog:null,//dialog的参数
			form:{
				id:"zend_f_id_"+Math.round(Math.random()*1000000),
				name:"zend_f_name_"+Math.round(Math.random()*1000000)
			}
			},arg
		);
	
		//dialog的HTML容器
		var Did,Ddiv;
		Did = "Did_" + Date.parse(new Date());
		Ddiv = "<div id='"+Did+"'></div>";
		
		//dialog的缺省按钮
		var dialogButtons = {
			"确定":function(event){
				var buttonT = $(event.target);
				buttonT.html("正在提交表单...").parent("button").attr({"disabled":"disabled"});
				//查找form
				var formT = (arg.form.id == null) ? null : $("form#"+arg.form.id);
				formT = formT || (arg.form.name == null) ? null : $("form [href='"+arg.form.id+"']");
				formT = formT || $(this).find("form");
				
				var reStr = formT.formSerialize ? formT.formSerialize() : formT.serialize();
				$.ajax({
					url: formT.attr("action") || arg.url,
					data:reStr,
					dataType:"json",
					type:formT.attr("method") || "POST",
					success:function(data) {
						data.msg = data.msg || data.message;
						if (data.error) { //校正一下，走这个
							data.status = "error";
							data.msg = data.error;
						}
						if (data.status == "success") data.status = 1;
						if (data.status == "success") {
							alert(data.msg);
							buttonT.html("OK");
							if(e.grid){
								e.grid.populate();
								window.setTimeout(function(){$("#"+Did).dialog("close");},1200);
							}
						} else if (data.status === "error") {
							alert(data.msg);
							buttonT.html("确定").parent("button").attr({"disabled":false});
						} else if(data.status > 0){
				        	$("#"+Did).html(data.msg);
				        	buttonT.html("OK");
				        	if(e.grid){
				        		e.grid.populate();
				        		window.setTimeout(function(){$("#"+Did).dialog("close");},1200);
				        	}
				        	zendform.successSuccess && arg.successSuccess.apply(this, arguments);
				        }else{
				        	zendform.zendRenderCreatForm(data['form'],true,Did,e,arg);
					        $("<div>ERROR!"+data.msg+"</div>").dialog({title:"ERROR!",height: 140,modal: true});
				        	buttonT.html("确定").parent("button").attr({"disabled":false});
				        }
				    },
				    error:function(){
				    	$("<div>ERROR!<br>服务错误！可能是网络忙！</div>").dialog({title:"ERROR!",height: 140,modal: true});
				    	buttonT.html("确定").parent("button").attr({"disabled":false});
				    }
				});
			},
			"取消":function(){$(this).dialog("close")}	
		};
		
		//dialog的缺省配置
		var dialogOption = $.extend({
			title:"新增",
			modal:true,
			buttons:dialogButtons,
			close:function(){$(this).remove()}
		},arg.dialog);
		
		var rs ;
		//切点A :beforeDialogAppend dialog的div被放置在body中之前
		if(typeof arg.beforeDialogAppend == "function"){
			//切点A的回调参数 e，arg，dialog的最终参数项目,在其中，可改变Ddiv变量来改变div的html内容
			rs = arg.beforeDialogAppend(e,arg,Ddiv,dialogOption) || false;
			//如果回调返回的是cancel，那么终止程序。
			if(rs == "cancel") return;
			else if(rs != "") Ddiv = rs;
		}
		//切点A 结束
		
		var _dialog = $(Ddiv).appendTo("body").dialog(dialogOption);
		
		//切点 B :afterDialogAppend dialog的div被放置在body中之后 也是渲染表单之前
		if(typeof arg.afterDialogAppend == "function"){
			//切点A的回调参数 e，arg，dialog的最终参数项目,在其中，可改变Ddiv变量来改变div的html内容
			rs = arg.afterDialogAppend(e,arg,_dialog,dialogOption) || false;
			//如果回调返回的是cancel，那么终止程序。
			if(rs == "cancel") return;
		}
		//切点B 结束
	
		//渲染表单
		this.zendRenderCreatForm(arg.url,false,Did,e,arg);		
	}	
	
	/**
	 * 标记某个元素为可上传文件的元素
	 */
	,uploadTag:function($element,tagButtonId){
		tagButtonId = tagButtonId || "uploadIco_" + Math.randomInt();
		//var htmltemp = "<div style='width: 40px;position: absolute;background: red;padding: 3px;left: 192px;'> upload </div>";
		var htmltemplete = "<div style='width: 18px;position: relative;left: 141px;background-color: #FFF;margin: 2px;top: -22px;height: 18px;'> <span id='"+tagButtonId+"' >&nbsp;</span></div>";
		$element.after(htmltemplete);
		return tagButtonId;
	}
	/**
	 * 确定上传进度条位置
	 */
	,uploadingTag:function($element,progressTarget){
		progressTarget = progressTarget || "progressTarget_" + Math.randomInt();
		var htmltemplete2= "<input id='"+progressTarget+"' style='background: #AEC2E4;position: relative; top: -23px;text-align: right;' value='上传中...' readonly class='uploading ui-widget-content'>";
		$element.after(htmltemplete2);
		return progressTarget;
	}
	,uploadedTag:function($element){
		var htmltemplete2= "<input style='background: #AEC2E4;position: relative; top: -23px;text-align: right;' value='上传中...' readonly class='ui-widget-content'>";
		$element.after(htmltemplete2);
	}
	
	/**
	 * 装饰上传域(需要swfupload和handle)
	 * 第一个参数是swf的参数，用于覆盖缺省值，第二个参数是用户提交数据的附件在post中的参数
	 */
	,appendSWFupload : function(swfupArg,userArg){
		try{
			swfu = new SWFUpload($.extend({
				// Backend Settings
				upload_url: BASEURL + "/file/upload",
				post_params: $.extend({"PHPSESSID": PHPSESSID,"ju_element":"xxx"},userArg),
	
				// File Upload Settings
				file_size_limit : "2 MB",	// 2MB
				file_types : "*.*",
				file_types_description : "Every File You Want",
				file_upload_limit : "0",
	
				//upload_start_handler : fileUpSatrt,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : zendform.uploadSuccess,
				upload_complete_handler : uploadComplete,
	
				// Button Settings
				button_image_url : BASEURL + "/js/swfupload/SmallSpyGlassWithTransperancy_17x18.png",
				button_placeholder_id : "",
				button_width: 18,
				button_height: 18,
				button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
				button_cursor: SWFUpload.CURSOR.HAND,
				
				// Flash Settings
				flash_url : BASEURL + "/js/swfupload/swfupload.swf",
	
				custom_settings : {
					upload_target : ""
				},
				
				//customSettings
				customSettings : {
						progressTarget : ""
						,cancelButtonId : "btnCancel"
				},
				
				// Debug Settings
				debug: false
			},swfupArg));
		}catch(e){
			//这里的错误被隐藏
		}
		
		/*$("#sltdiv").insertAfter("#mag_thumbnail");
		$("#mag_thumbnail").css("float","left");*/
	}
	//上传成功共
	,uploadSuccess : function(file, serverData) {
		try{
			var response = $.parseJSON(serverData);
		}catch(ex){
			response = serverData;
		}
		try {
			if(response.FILEID){
				if(response.request){
					$("#" + response.request.ju_element).val(response.FILEID).next(".uploading").remove();
				}
				//progress.setStatus("Thumbnail Created.");
				var progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.toggleCancel(false);
			} else {
				this.uploadError(file, 1001, serverData);
			}
		} catch (ex) {
			this.debug(ex);
		}
	}
}

/**
 * flexgrid 通用的方法
 */
var gridHelper = {
	Cash : function(a,b){
		window.test = a;
		a.innerHTML = tools.formatCash(a.innerHTML);
	},
	Bool : function(a,b){
		a.innerHTML = (a.innerHTML > 0)?"是":"否";
	},
	Gender : function(a,b){
		a.innerHTML = (a.innerHTML > 0)?"男":"女";
	},
	Img : function(a,b){
		a.innerHTML = "<img width='"+$(a).width()+"' src='"+BASEURL+"/"+a.innerHTML+"' onError='tools.errorImg(this)'/>";
	},
	Extention:function(a,b){
		var rs = [];
		rs = a.innerHTML.split(".");
		a.innerHTML = rs[rs.length-1];
	},
	Aapprove : function(a,b){
		var s = a.innerHTML,rs="";
		if(s>0){
			rs = "<font color='green'>通过</font>";
		}else if(s==0){
			rs = "<font color='blue'>未审</font>";
		}else{
			rs = "<font color='red'>未通过</font>";
		}
		a.innerHTML = rs;
	}	
}

//flex方法结束

/**
 * 全局方法
 */
var tools = {
	formatCash : function(cash){
		try{
			cash = Number(cash);
			if(isNaN(cash)){
				return "0.00";
			}else{
				//return cash.toFixed(2);
				//一下注释为格式化为逗点
				var cashStr = String(cash.toFixed(2));
				cashStr = cashStr.replace(/\B(?=([\d]{3})+[$,\.])/g,',');
				return cashStr;
			}
		}catch(e){
			alert("格式化资金样式异常");
		}
	}
	,errorImg : function(element){
		element.src = BASEURL + "/images/nopic.png";
		element = null;
	}
};

/**
 * 消息工具
 */
var msgTools = {
	/*
	 * 切换读取状态 
	 */
	toggleState:function(id,callback){
		if(id){
			$.ajax({
				url:BASEURL + "/msg/togglestate",
				data:{id:id},
				type:"post",
				dataType:"json",
				success:function(data){
					if(typeof callback == "function"){
						callback(data);
					}
				},
				error:function(){
				}
			});
		}
	}
};

/**
 * 邮件工具
 */
var mailTools = {
	/**
	 * 设置阅读状态
	 * @param int id 邮件的id
	 * @param int state 0未读，1已读
	 * @param okcallback 成功之后的回调
	 * @param failcallback 失败之后的回调
	 */
	setState:function(id,state,okCallback,failCallback){
		var data = {"id":id,"state":state};
		$.ajax({
			url:BASEURL + '/mail/setstate',
			data:data,
			type: 'post',
			dataType:'json',
			success:function(data){
				if(data.status){
					//设置成功
					(typeof okCallback == "function") && okCallback(data);
				}else{
					(typeof failCallback == "function") && failCallback(data);
					alert("设置失败 : " + data.msg);
				}
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				(typeof failCallback == "function") && failCallback(XMLHttpRequest, textStatus, errorThrown);
				alert("设置失败");
			}
		});
	}
	
	/**
	 * 重新匹配客户邮件
	 * @param okcallback 成功之后的回调
	 * @param failcallback 失败之后的回调
	 */
	,matchcustomer:function(okCallback,failCallback){
		$.ajax({
			url:BASEURL + '/mail/matchcustomer',
			type: 'post',
			dataType:'json',
			success:function(data){
				if(data.status){
					//设置成功
					(typeof okCallback == "function") && okCallback(data);
				}else{
					(typeof failCallback == "function") && failCallback(data);
				}
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				(typeof failCallback == "function") && failCallback(XMLHttpRequest, textStatus, errorThrown);
			}
		});
	}
	/**
	 * send mail background
	 */
	,startSendPorcess:function(){
		$.ajax({
			url:BASEURL + "/mail/sendmail"
		});
	}
	/**
	 * recive mail background
	 */
	,startRecivePorcess:function(){
		$.ajax({
			url:BASEURL + "/mail/recivemail"
		});
	}
};
/**
 * 全局中执行
 */
Number.prototype.toFixed = function(d){
	var s=this+"";
	if(!d)d=0;
	if(s.indexOf(".")==-1)s+=".";s+=new Array(d+1).join("0");
	if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+ (d+1) +"})?)\\d*$").test(s))
	{
		var s="0"+ RegExp.$2, pm=RegExp.$1, a=RegExp.$3.length, b=true;
		if (a==d+2){
			a=s.match(/\d/g); if (parseInt(a[a.length-1])>4)
			{
				for(var i=a.length-2; i>=0; i--) {a[i] = parseInt(a[i])+1;
					if(a[i]==10){a[i]=0; b=i!=1;} else break;
				}
			}
			s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
		}
		if(b)s=s.substr(1);
			return (pm+s).replace(/\.$/, "");
	}
	return this+"";
}; 
/**
 * 返回指定范围内的整形随机数
 * @param min
 * @param max
 * @returns Int
 */
Math.randomInt = function(min,max){
	min = Number((typeof min == "undefined")?0:min);
	min = isNaN(min)?0:min;
	max = Number((typeof max == "undefined")?1000:max);
	max = isNaN(max)?1000:max;
	
	return parseInt(Math.random()*(min-max)+max);
}
$(function(){
	//处理错误提示，点击出错的提示就把它remove掉
	$("ul.errors").live("click",function(){
		$(this).prev("input").focus();
		$(this).remove();
	});
	//处理错误提示，空间获取焦点就把提示remove掉
	$("ul.errors").prev("input").live("focus",function(){
		$(this).next("ul.errors").remove();
	});
});